var app = require('express');
var conn = require('../public/javascripts/connect');
var judge_login = require('../public/javascripts/judge_login');
var router = app.Router();
let _ = require('underscore');
let server = require('http').Server(app());
var io = require('socket.io')(server);
let roomInfo = {}, waitingRes, Queueid = {};
io.on('connection', function (socket) {
    console.log(socket.id, "连上了服务器,现在报上你的名字来");
    socket.on('setRoom', function (data) {
        var name = data.roomId;
        console.log('我的名字是: ', name)
        roomInfo[name] = socket.id;//连上服务器的客户机roomInfo
        console.log("roomInfo", roomInfo);
    });
    socket.on('disconnect', function (data, index) {
        console.log("客户机已经断开", socket.id, index)
    });
});

let emitID = async (event, nameId, data) => {//客户机名字和要发给客户机的数据
    return new Promise((res, rej) => {
        let id = "id_" + parseInt(Math.random() * 10000);
        let toId = roomInfo[nameId];
        console.log("nameId", nameId)
        console.log("roomInfo", roomInfo)
        console.log("toId", toId)
        // nodejs的underscore扩展中的findWhere方法，可以在对象集合中，通过对象的属性值找到该对象并返回。
        var toSocket = _.findWhere(io.sockets.sockets, {id: toId});
        if (toSocket) {
            toSocket.emit(event, data)
        }
        Queueid[id] = res;
    });
}
router.post("/singleGrasp", async function (req, res, next) {
    console.log(44)
    if (req.body['field'] == "去年同期抓取" || req.body['field'] == "当月抓取值") {
        console.log(45)
        emitID("massage", "A1", req.body);
        res.json({"success": true})
    } else {
        res.json({"success": false})
    }
})
router.post("/singleGrasp", async function (req, res, next) {
    console.log(44)
    if (req.body['field'] == "去年同期抓取" || req.body['field'] == "当月抓取值") {
        console.log(45)
        emitID("massage", "A1", req.body);
        res.json({"success": true})
    } else {
        res.json({"success": false})
    }
})
server.listen(8001);
module.exports = router;